package com.concurrent.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author: zhouyang
 * @descrpition: 用合并任务来计算1-100的和 拆分子任务丢到线程里去
 * @time: 2019-05-10 13:48
 */
@Slf4j
public class ForkJoinTaskTest extends RecursiveTask<Integer> {
    private static final int threshold = 2;

    private int start;
    private int end;

    public ForkJoinTaskTest(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //如果任务足够小就开始计算
        boolean canCompute = (end-start)<=threshold;
        if(canCompute){
            for(int i=start;i<=end;++i) sum+=i;
        }else{//足够大就分割
            int mid = (start+end)/2;
            ForkJoinTaskTest left = new ForkJoinTaskTest(start,mid);
            ForkJoinTaskTest right = new ForkJoinTaskTest(mid+1,end);

            left.fork();//执行子任务
            right.fork();//执行子任务

            int leftResult = left.join();
            int rightResult = right.join();

            sum = leftResult+rightResult;//合并子任务
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        ForkJoinTaskTest test = new ForkJoinTaskTest(1,100);

        Future<Integer> res = forkJoinPool.submit(test);

        try {
            log.info("res is {}",res.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
